﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MapManager : MonoBehaviour
{
    // Start is called before the first frame update

    public GameObject[] outerWallArray;
    public GameObject[] floorArray;
    public GameObject[] wallArray;
    public GameObject[] foodArray;
    public GameObject[] enemyArray;
    public GameObject exitPrefab;

    public int minCountWall = 2;
    public int maxCountWall = 8;

    private Transform mapHolder;
    private List<Vector3> postionList = new List<Vector3>();

    private GameManager gameManagerScript;

    private int rows = 10;
    private int cols = 10;
    void Awake()
    {
        gameManagerScript = this.GetComponent<GameManager>();
        InitMap();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void InitMap()
    {

        //创建地图边框和地板
        mapHolder = new GameObject("Map").transform;
        for (int x = 0; x < cols; x++)
        {
            for (int y = 0; y < rows; y++)
            {
                GameObject toInstantiate = floorArray[Random.Range(0, floorArray.Length)];
                if (x==0||y==0||x==cols-1||y==rows-1)
                {
                    toInstantiate = outerWallArray[Random.Range(0, outerWallArray.Length)];
                }
                Instantiate(toInstantiate, new Vector3(x, y, 0f), Quaternion.identity, mapHolder);
            }
        }
        postionList.Clear();
        for (int x = 2; x < cols-2; x++)
        {
            for (int y = 2; y < rows-2; y++)
            {
                postionList.Add(new Vector3(x,y,0f));
            }
        }

        //创建障碍物
        int wallCount = Random.Range(minCountWall, maxCountWall + 1);//障碍物个数
        InstantiateRandomItem(wallCount, wallArray);

        //创建食物
        int foodCount = Random.Range(2, gameManagerScript.gameLevel*2+1);
        InstantiateRandomItem(foodCount, foodArray);

        //创建敌人
        int enemyCount = gameManagerScript.gameLevel/2;
        InstantiateRandomItem(enemyCount, enemyArray);
        //创建出口
        Instantiate(exitPrefab,new Vector3(cols-2,rows-2,0f),Quaternion.identity,mapHolder);
        
    }


    private Vector3 RandomPostion()
    {
        //随机取得一个位置
        int randomIndex = Random.Range(0, postionList.Count);
        Vector3 postion = postionList[randomIndex];
        postionList.RemoveAt(randomIndex);
        return postion;
    }

    
    private GameObject RandomPrefab(GameObject[] prefabs) //随机取得一个预制体
    {
        return prefabs[Random.Range(0, prefabs.Length)];
    }

    private void InstantiateRandomItem(int itemCount,GameObject[] itemPrefabs)
    {
        for (int i = 0; i < itemCount; i++)
        {
            Vector3 postion = RandomPostion();
            Instantiate(RandomPrefab(itemPrefabs), postion, Quaternion.identity, mapHolder);
        }

    }

}
